package com.rj.framework.transformer;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 类型转换注册表
 */
public class TransformationRegistry {
    private final Map<ClassPair, DataTransformer<?>> transformers = new ConcurrentHashMap<>();

    public <S, T> void registerTransformer(Class<S> sourceType, Class<T> targetType, DataTransformer<T> transformer) {
        transformers.put(new ClassPair(sourceType, targetType), transformer);
    }

    @SuppressWarnings("unchecked")
    public <S, T> DataTransformer<T> getTransformer(Class<S> sourceType, Class<T> targetType) {
        return (DataTransformer<T>) transformers.get(new ClassPair(sourceType, targetType));
    }

    public <T> T transform(Object source, Class<T> targetType) {
        if (source == null) return null;
        if (targetType.isInstance(source)) {
            return targetType.cast(source);
        }
        DataTransformer<T> transformer = getTransformer(source.getClass(), targetType);
        if (transformer != null) {
            return transformer.transform(source);
        }

        throw new IllegalArgumentException("No transformer found from " + source.getClass().getName() + " to " + targetType.getName());
    }


    private static class ClassPair {
        private final Class<?> source;
        private final Class<?> target;

        public ClassPair(Class<?> source, Class<?> target) {
            this.source = source;
            this.target = target;
        }
    }
}